<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .big {
            height: 200px;
            width: 200px;
            background-color: red;
            margin: 100px auto;
            position: relative;
        }
        
        .small {
            height: 50px;
            width: 50px;
            background-color: green;
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="big">
        <div class="small"></div>
    </div>
</body>
<script>
    var big = document.querySelector('.big');
    var small = document.querySelector('.small');
    var halfX = small.offsetWidth / 2;
    var halfY = small.offsetHeight / 2;
    big.addEventListener('mousemove', function(e) {
        //1.先获取鼠标在大盒子中的坐标
        var x = e.pageX - this.offsetLeft - halfX;
        var y = e.pageY - this.offsetTop - halfY;
        //盒子移动的距离 =大盒子宽度-小盒子的宽度
        var moveLeft = big.offsetWidth - small.offsetWidth;
        var moveTop = big.offsetHeight - small.offsetHeight;
        if (x > moveLeft) {
            x = moveLeft;
        }
        if (x < 0) {
            x = 0;
        }
        if (y > moveTop) {
            y = moveTop;
        }
        if (y < 0) {
            y = 0;
        }
        console.log(x, y);
        small.style.left = x + 'px';
        small.style.top = y + 'px';

    })
</script>

</html>